import type { RouteLocationRaw, RouteLocationPathRaw } from 'vue-router';
import router from '@/router/index';

// 跳转考古加地址
const KGJ_HOST = 'https://www.kaogujia.com';

const regExternalUrl = /^https?:\/\/.*$/;
export const isExternalUrl = (url: string) => regExternalUrl.test(url);

const resolveHref = (options: RouteLocationRaw): string => router.resolve(options)?.href;

export default class JumpService {
  /**
   * 页面间的跳转
   * @param {RouteLocationRaw} options 跳转参数
   * @param {boolean} newWindow 是否打开新页面(默认打开)
   * @returns {void}
   */
  public static jump(options: RouteLocationRaw | string, newWindow = true) {
    if (typeof options === 'string' && regExternalUrl.test(options)) {
      // 外链
      if (newWindow) window.open(options, '_blank');
      else location.href = options;
      return;
    }

    let routeOptions = options;
    // routeName
    if (typeof options === 'string') routeOptions = { name: options };

    if (newWindow) window.open(resolveHref(routeOptions), '_blank');
    else router.push(routeOptions);
  }

  /**
   * 页面间的跳转
   * @param {RouteLocationRaw} options 跳转参数
   * @param {boolean} newWindow 是否打开新页面(默认打开)
   * @returns {void}
   */
  public static jumpToPage(options: RouteLocationRaw, newWindow = true) {
    if (newWindow) {
      window.open(resolveHref(options), '_blank');
    } else {
      router.push(options);
    }
  }

  /**
   * 跳转到kgj
   * @param {RouteLocationPathRaw} options 跳转参数
   * @param {boolean} newWindow 是否打开新页面(默认打开)
   * @returns {void}
   */
  public static jumpToKgj(options: RouteLocationPathRaw, newWindow = true) {
    if (newWindow) {
      window.open(KGJ_HOST + options.path);
    } else {
      window.location.href = KGJ_HOST + options.path;
    }
  }

  /** 打开考古加--达人-达人概览 **/
  public static jumpToKgjDaren(params: { uid: number | string }) {
    JumpService.jumpToKgj({ path: `/darenDetails/darenOverview/${params.uid}` });
  }

  /** 打开考古加--商品-商品概览 **/
  public static jumpToKgjProduct(params: { product_id: number | string }) {
    JumpService.jumpToKgj({ path: `/productDetails/productOverview/${params.product_id}` });
  }

  /** 打开考古加--小店-小店概览 **/
  public static jumpToKgjShop(params: { shop_id: number | string }) {
    JumpService.jumpToKgj({ path: `/smallShopDetails/smallShopOverview/${params.shop_id}` });
  }

  /** 打开考古加--品牌-品牌概览 **/
  public static jumpToKgjBrand(params: { brand_id: number | string }) {
    JumpService.jumpToKgj({ path: `/brandDetails/brandOverview/${params.brand_id}` });
  }

  /** 打开考古加--达人-达人概览 **/
  public static jumpToKgjLive(params: { uid: number | string; room_id: number | string; date_code: number | string }) {
    JumpService.jumpToKgj({ path: `/liveDetails/${params.room_id}/${params.uid}/${params.date_code}` });
  }
}
